﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PKSpeed
{
    /// <summary>
    /// 命令的Hash表
    /// </summary>
    class HashCommand
    {
        /// <summary>
        /// Hash表
        /// </summary>
        public static readonly PKCommand.Operation[] Operators=new PKCommand.Operation[14];
        //Hash表键值对
        private static readonly Hashtable Hashtable = new Hashtable();

        /// <summary>
        /// 初始化Hash表
        /// </summary>
        /// <returns></returns>
        public static bool InitializeHashTable()
        {
            String[] cmds = { "useradd", "passwd", "su", "logout", "ls", "cp", "mv", "mkdir", "cd", "rm",
                                "cat", "find", "exit", "alias" };
            //键值对
            for (int i = 0; i < 14;i++ )
            {
                Hashtable.Add(cmds[i], i);
            }
            //加载操作委托Hash表项
            Operators[0] = UserOperation.UserAdd;
            Operators[1] = UserOperation.Passwd;
            Operators[2] = UserOperation.SU;
            Operators[3] = UserOperation.Logout;
            Operators[4] = FileOperation.Ls;
            Operators[5] = FileOperation.Cp;
            Operators[6] = FileOperation.Mv;
            Operators[7] = FileOperation.MkDir;
            Operators[8] = FileOperation.Cd;
            Operators[9] = FileOperation.Rm;
            Operators[10] = FileOperation.Cat;
            Operators[11] = FileOperation.Find;
            Operators[12] = ExtraOperation.Exit;
            Operators[13] = ExtraOperation.Alias;
            return true;
        }
        
        /// <summary>
        /// Hash算法，返回Hash值
        /// </summary>
        /// <param name="commandName">命令字符串</param>
        /// <returns>Hash值</returns>
        public static int GetHashCode(String commandName)
        {
            try
            {
                return (int) Hashtable[commandName];
            }
            catch
            {
                //若表中不存在则返回-1
                return -1;
            }
        }
    }
}
